package com.dodock.banglapapers.server.helper;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.xml.sax.SAXException;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class DDNNewsListBDProtidin implements DDNNewsListInterface {

	@Override
	public String GenerateNewsList(String categoryid) throws IOException,
			SAXException, ParserConfigurationException {
		JsonArray array = new JsonArray();
		Document doc;
		String url = Settings.WWW_BD_PROTIDIN_COM + categoryid;
		// System.out.println("categoryid : " + categoryid + " , URL : " + url);
		try {
			Connection.Response response = Jsoup
					.connect(url)
					.userAgent(
							"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
					.timeout(10000).execute();
			doc = response.parse();

			Elements mastHeads = null;
			mastHeads = doc
					.select("div[style=position:relative; margin-bottom:15px; background:#666]");
			parseNewsElement(array, mastHeads);

			mastHeads = doc.select("div[style=margin-bottom:15px;]");
			parseNewsElement(array, mastHeads);

			mastHeads = doc.select("div[style=margin-bottom:15px]");
			parseNewsElement(array, mastHeads);
			return array.toString();
		} catch (Exception e) {
			System.out.println(e.toString());
			return "[]";
		}
	}

	private void parseNewsElement(JsonArray array, Elements elements) {
		JsonObject obj;
		for (Element element : elements) {
			obj = new JsonObject();
			// System.out.println("--------New News Item---------");
			Elements imgElements = element.select("img");
			if (!imgElements.isEmpty()) {
				String image = imgElements.first().attr("src");
				obj.addProperty("image", image);
				// System.out.println("Image : " + image);
			}
			Elements newsElements = element.select("a");
			if (!newsElements.isEmpty()) {
				Element newsElement = newsElements.first();
				String id = newsElement.attr("href");
				obj.addProperty("id", id);
				String title = newsElement.text();
				obj.addProperty("title", title);

				// System.out.println("ID : " + id);
				// System.out.println("title : " + title);
				array.add(obj);
			}
		}
	}

}
